package com.logicwin.aibala.services.file;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

public final class ImageFileCache {
	private int myCapacity;
	private ConcurrentHashMap<String, String> firstMap = null;
	private ConcurrentHashMap<String, String> secondMap = null;
	
	public ImageFileCache(int capacity) {
		this.myCapacity = capacity;
		this.firstMap = new ConcurrentHashMap<String, String>();
		this.secondMap = new ConcurrentHashMap<String, String>();
	}
	
    public String get(String fileurl) {
    	String filepath = this.firstMap.get(fileurl);
    	if(null == filepath) {
    		filepath = this.secondMap.remove(fileurl);		
    		if(null != filepath) {
    			this.firstMap.put(fileurl, filepath);
    		}
    	}
    	return filepath;
    }
    
    public void put(String fileurl, String filepath) {
    	HashMap<String, String> tmpMap = null;
    	
    	if(this.firstMap.size() >= this.myCapacity) {
    		tmpMap = new HashMap<String, String>();
    		tmpMap.putAll(this.secondMap);
    		this.secondMap.clear();
    		this.secondMap.putAll(this.firstMap);
    		this.firstMap.clear();
    	}
    	this.firstMap.put(fileurl, filepath);
    	
    	if(null != tmpMap) {
    		Iterator<Entry<String, String>> ite = tmpMap.entrySet().iterator();
    		while(ite.hasNext()) {
    			Entry<String, String> entry = ite.next();
    			File f = new File(entry.getValue());
    			f.deleteOnExit();
    		}
    		tmpMap.clear();
    	}
    }
}
